﻿using CommonLib.Base;
using CommonLib.CodeEntity;

namespace SQLServer.Convert;

public class TriggerConvert(TriggerCodeEntity trigger) : BaseConvert
{

    private readonly TriggerCodeEntity Trigger = trigger;

    protected override List<string> Run()
    {
        var list = new List<string>()
        {
            $"CREATE TRIGGER {Trigger.Name} {Trigger.Timing} ON {Trigger.Table}",
        };
        if (Trigger.IsRow) list[0]= $"{list[0]} FOR EACH ROW";
        list.Add($"EXECUTE FUNCTION {Trigger.Name}_FUNC()");
        list.Add(" ");

        list.Add($"CREATE OR REAPLACE FUNCTION {Trigger.Name}_FUNC()");
        list.Add("RETURN TRIGGER AS $$");
        if (Trigger.Declare != null)
        {
            list.Add("DECLARE");
            Trigger.Declare.ForEach(f => list.Add(f.SqlLine()));
        }
        list.AddRange(Trigger.Body!.SqlList());
        //TODO RETURN OLD|NEW
        int idx = list.FindLastIndex(s=>s.Equals("EXCEPTION"));
        if (idx < 0) idx = list.Count - 2; 
        if (Trigger.Timing.StartsWith("BEFORE")) list.Insert(idx, "RETURN NEW;");
        else list.Insert(idx, "RETURN OLD;");
        list.Add("$$");
        list.Add("LANGUAGE \"plpgsql\";");
        return list;
    }
}
